#include "FontDesc.h"
#include "Resource.h"

namespace Resource
{
	static FontDesc* loadFontDescFNT(const char *name);
	
	FontDesc* loadFontDesc(const char *name)
	{
		ASSERT(name);
		
		const char *ext = strrchr(name, '.');
		if (!ext)
		{
			LOG_ERROR("Invalid font '%s' extension\n", name);
			return NULL;
		}
		
		if (strcmp(ext, ".fnt") == 0)
			return loadFontDescFNT(name);
		
		LOG_ERROR("Not supported font '%s' extension '%s'\n", name, ext);
		return NULL;
	}
	
	static FontDesc* loadFontDescFNT(const char *name)
	{
		ASSERT(name);
		
		File *file = loadFile(name);
		if (file == NULL)
			return NULL;
		
		if (file->size < sizeof(FontHead))
		{
			LOG_ERROR("Invalid font description in '%s'\n", name);
			freeFile(file);
			return NULL;
		}
		
		const FontHead *head = (const FontHead *)file->data;
		if (file->size < (sizeof(FontHead) + head->width * head->height * 2))
		{
			LOG_ERROR("Invalid font data in '%s'\n", name);
			freeFile(file);
			return NULL;
		}
		
		FontDesc *font = new FontDesc(head->width, head->height);
		memcpy(font, head, sizeof(FontHead));
		memcpy(font->bitmap, file->data + sizeof(FontHead), head->width * head->height * 2);
		
		freeFile(file);
		return font;
	}
}
